<template>
  <div class="announcement-detail">
    <Header />
    <div class="detail-content">
      <!-- 返回按钮 -->
      <div class="back-section">
        <el-button @click="goBack" type="text" size="large">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
      
      <el-row :gutter="30">
        <!-- 左侧主要内容 -->
        <el-col :span="18">
          <el-card class="detail-card">
            <div class="article-header">
              <el-tag size="small" :type="getTagType(announcement.classification)">
                {{ getClassificationLabel(announcement.classification) }}
              </el-tag>
              <h1 class="article-title">{{ announcement.title }}</h1>
              <div class="article-meta">
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>发布者：{{ announcement.name }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>发布时间：{{ formatTime(announcement.createTime) }}</span>
                </div>
              </div>
            </div>

            <div class="article-content" v-html="getTextContent(announcement.text)"></div>

            <!-- 文章底部 -->
            <div class="article-footer">
              <div class="tags">
                <el-tag 
                  v-for="tag in announcement.tags" 
                  :key="tag"
                  effect="plain"
                  size="small"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧相关文章 -->
        <el-col :span="6">
          <el-card class="related-card">
            <template #header>
              <div class="card-header">
                <h3>作者的其他文章</h3>
              </div>
            </template>
            <div class="related-list">
              <div 
                v-for="item in authorArticles" 
                :key="item.announcementId"
                class="related-item"
                @click="viewArticle(item.announcementId)"
              >
                <h4 class="related-title">{{ item.title }}</h4>
                <div class="related-meta">
                  <span>{{ formatTime(item.createTime) }}</span>
                </div>
              </div>
              <el-empty 
                v-if="authorArticles.length === 0"
                description="暂无其他文章" 
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAnnouncementDetail, getAuthorAnnouncements, type Announcement } from '../../api/announcement'
import Header from '../../components/header.vue'
import Footer from '../../components/footer.vue'
import { ArrowLeft, User, Clock } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const announcement = ref<Announcement>({
  announcementId: 0,
  title: '',
  name: '',
  classification: '',
  createTime: '',
  text: ''
})
const authorArticles = ref<Announcement[]>([])

// 获取文章详情
const fetchDetail = async () => {
  try {
    const res = await getAnnouncementDetail(Number(route.params.id))
    if (res.code === '200') {
      announcement.value = res.data
      // 获取作者的其他文章
      fetchAuthorArticles()
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
  }
}

// 获取作者的其他文章
const fetchAuthorArticles = async () => {
  try {
    const res = await getAuthorAnnouncements(announcement.value.name)
    if (res.code === '200') {
      // 过滤掉当前文章
      authorArticles.value = res.data
        .filter(article => article.announcementId !== announcement.value.announcementId)
        .slice(0, 5) // 最多显示5篇
    }
  } catch (error) {
    console.error('获取作者文章失败:', error)
  }
}

// 返回列表
const goBack = () => {
  router.push('/announcement')
}

// 获取分类标签类型
const getTagType = (classification: string) => {
  const types: { [key: string]: string } = {
    'emotion': 'danger',
    'study': 'warning',
    'work': 'info',
    'family': 'success',
    'social': 'primary',
    'disorder': 'error'
  }
  return types[classification] || ''
}

// 获取分类显示文本
const getClassificationLabel = (classification: string) => {
  const labels: { [key: string]: string } = {
    'emotion': '情感困扰',
    'study': '学业压力',
    'work': '职场压力',
    'family': '家庭关系',
    'social': '人际关系',
    'disorder': '心理障碍'
  }
  return labels[classification] || '其他'
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取文本内容
const getTextContent = (text: string) => {
  // 如果text为undefined、null或空字符串，返回空字符串
  if (!text || typeof text !== 'string') return ''

  try {
    const textObj = JSON.parse(text)
    // 确保textObj.text是字符串
    if (typeof textObj.text === 'string') {
      return textObj.text.replace(/([。？！])/g, '$1<br><br>')
    }
    // 如果textObj.text不是字符串，使用原始text
    return text.replace(/([。？！])/g, '$1<br><br>')
  } catch {
    // 如果JSON解析失败，直接处理原始text
    return text.replace(/([。？！])/g, '$1<br><br>')
  }
}

// 查看文章
const viewArticle = (id: number) => {
  router.push(`/announcement/${id}`)
  // 滚动到页面顶部
  window.scrollTo(0, 0)
}

onMounted(() => {
  fetchDetail()
})

// 监听路由变化，重新获取数据
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      fetchDetail()
    }
  }
)
</script>

<style scoped>
.announcement-detail {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.detail-content {
  flex: 1;
  width: 1200px;
  margin: 84px auto 40px;
  padding: 0 20px;
}

.detail-card {
  padding: 30px;
  min-height: 800px;
  display: flex;
  flex-direction: column;
}

.back-section {
  margin-bottom: 30px;
}

.article-header {
  margin-bottom: 40px;
  text-align: center;
  padding: 20px 40px;
  border-bottom: 1px solid #ebeef5;
}

.article-title {
  font-size: 28px;
  color: #2c3e50;
  margin: 20px 0;
  line-height: 1.4;
  font-weight: 600;
}

.article-meta {
  color: #909399;
  font-size: 14px;
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  margin-top: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.meta-item span {
  font-size: 14px;
}

.article-content {
  font-size: 16px;
  line-height: 1.8;
  color: #2c3e50;
  margin: 0;
  padding: 40px;
  flex: 1;
  text-align: justify;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.article-content :deep(p) {
  margin-bottom: 1.5em;
  text-indent: 2em;
}

.article-content :deep(br) {
  display: block;
  content: "";
  margin-top: 0.5em;
}

.article-footer {
  padding: 20px 40px;
  border-top: 1px solid #ebeef5;
  margin-top: auto;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 相关文章卡片样式 */
.related-card {
  position: sticky;
  top: 100px;
  max-height: 800px;
  overflow-y: auto;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #2c3e50;
}

.related-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px 0;
}

.related-item {
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.related-item:hover {
  background-color: #f5f7fa;
}

.related-title {
  font-size: 14px;
  color: #2c3e50;
  margin: 0 0 8px;
  line-height: 1.4;
}

.related-meta {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 12px;
}
</style> 